<template>
  <div class="sso-loading-container" v-if="true">
    <div class="loading-content">
      <div class="spinner"></div>
      <p class="loading-text">登录中...</p>
    </div>
  </div>
</template>

<script>
import Vue from 'vue'
import { getAction } from '@/api/manage'

import { mapActions } from 'vuex'
import { Notify } from 'vant';

export default {
  components: {},
  data() {
    return {
      showLoading: false,
      model: {
        username: '',
        inputCode: '',
      },
      requestCodeSuccess: false,
    }
  },
  created() {
    console.log('已进入')

    const sessionid = this.getCookie('sessionid')
    console.log(sessionid);
    if (sessionid != null && sessionid != '') {
      this.model.username = sessionid
      this.model.inputCode = "zwtLogin"
      this.handleSubmit()
    }

    const qwtoken = this.getQueryString('token')
    console.log(qwtoken);
    if (qwtoken != null && qwtoken != '') {
      this.model.username = qwtoken
      this.model.inputCode = "qwLogin"
      this.handleSubmit()
    }

    if ((sessionid == null) && (qwtoken == null)) {
      alert("未找到sessionId或token，请重新进入！")
    }

  },
  methods: {
    // 显示加载页
    show() {
      this.showLoading = true;
    },
    // 隐藏加载页（跳转后可能用不到，主要靠跳转自动刷新页面）
    hide() {
      this.showLoading = false;
    },


    ...mapActions(['Login']),
    getQueryString(name) {
      var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
      var reg_rewrite = new RegExp("(^|/)" + name + "/([^/]*)(/|$)", "i");
      var r = window.location.search.substring(1).match(reg);
      var q = window.location.pathname.substring(1).match(reg_rewrite);
      if (r != null) {
        return r[2];
      } else if (q != null) {
        return q[2];
      } else {
        return null;
      }
    },
    getCookie(name) {
      let arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
      if (arr = document.cookie.match(reg))
        return arr[2];
      else
        return null;
    },

    //登录
    handleSubmit() {
      let loginParams = {
        username: this.model.username,
        captcha: this.model.inputCode
      }
      localStorage.clear()
      sessionStorage.clear()
      console.log('登录参数', loginParams)
      console.log('登录参数==url', window.location.href)
      this.Login(loginParams).then((res) => {
        console.log('221111', res)
        this.requestSuccess(res.result)
      }).catch((err) => {
        this.requestFailed(err)
      })
    },

    // 登录后台成功
    requestSuccess(loginResult) {
      this.$store.dispatch('saveTenant', '')
      this.loginSuccess()
    },
    //登录后台失败
    requestFailed(err) {
      let description = ((err.response || {}).data || {}).message || err.message || '请求出现错误，请重新进入！'
      this.$notify({ type: 'error', message: description })
      this.loginBtn = false
    },
    loginSelectOk() {
      this.loginSuccess()
    },
    //登录成功
    loginSuccess() {
      console.log("🚀 ~ loginSuccess ~ window.location.href:", window.location.href)
      let redirectUrl = this.getRedirectUrl(window.location.href)
      console.log("🚀 ~ loginSuccess ~ redirectUrl:", redirectUrl)
      if (redirectUrl) {
        //先清空缓存
        localStorage.removeItem('$gridId')
        sessionStorage.removeItem('classifyType')
        sessionStorage.removeItem('isSso')
        localStorage.removeItem('$GRID_NAME')
        localStorage.removeItem('$dialogFinish')
        localStorage.removeItem('$dataPermission')
        // window.location.href = redirectUrl
        //获取参数
        // 获取路径部分
        console.log("🚀 ~ loginSuccess ~ this.parseUrl(redirectUrl):", this.parseUrl(redirectUrl))
        const goUrl = this.parseUrl(redirectUrl).url
        console.log("🚀 ~ loginSuccess ~ goUrl:", goUrl)
        // 获取查询参数
        localStorage.removeItem('$gridId')
        sessionStorage.setItem('classifyType', this.parseUrl(redirectUrl).pendingTypeId)
        console.log("🚀 ~ loginSuccess ~ searchParams.get('pendingTypeId'):", this.parseUrl(redirectUrl).pendingTypeId)
        console.log("🚀 ~ loginSuccess ~ searchParams.get('gridCode'):", this.parseUrl(redirectUrl).gridCode)

        localStorage.setItem('$gridId', this.parseUrl(redirectUrl).gridCode)
        sessionStorage.setItem('isSso', 'true')
        window.location.href = goUrl

      } else {
        this.$router.push({ path: '/' }).catch(() => {
          console.log('登录跳转首页出错')
        })
        this.$notify({ type: 'success', message: `${timeFix()}，欢迎回来` })
      }

    },
    parseUrl(url) {
      // 提取路径部分，直到最后一个 '-' 之前的内容
      const pathPart = url.split('-')[0];

      // 提取参数部分，从最后一个 '-' 之后的内容
      const paramPart = url.split('-').slice(1).join('-');

      // 提取参数
      const params = {};
      const paramPairs = paramPart.split('-');
      paramPairs.forEach(pair => {
        const [key, value] = pair.split('=');
        params[key] = value;
      });

      return {
        url: pathPart,
        pendingTypeId: params.pendingTypeId || '',
        gridCode: params.gridCode || ''
      };
    },
    //单点详情页
    getRedirectUrl() {
      try {
        // 先获取原始的 redirectUrl 参数
        const redirectUrlEncoded = this.getQueryString('redirectUrl');
        console.log("🚀 ~ getRedirectUrl ~ redirectUrlEncoded:", redirectUrlEncoded)

        if (redirectUrlEncoded) {
          // 解码 URL
          let redirectUrl = decodeURIComponent(redirectUrlEncoded);

          // 去除 source=WeiXin 参数（多种情况处理）
          const urlObj = new URL(redirectUrl);

          // 删除 source 参数
          urlObj.searchParams.delete('source');

          // 重新构建 URL
          redirectUrl = urlObj.toString();

          return redirectUrl;
        } else {
          return '';
        }
      } catch (error) {
        console.error('解析 redirectUrl 错误:', error);
        return '';
      }
    }
  },
}
</script>
<style scoped>
.sso-loading-container {
  position: fixed;
  top: 0;
  left: 0;
  width: 100vw;
  height: 100vh;
  background: #fff;
  z-index: 9999;
  /* 确保在最上层 */
  display: flex;
  justify-content: center;
  align-items: center;
}

.loading-content {
  text-align: center;
}

/* 加载动画（简单的旋转效果） */
.spinner {
  width: 40px;
  height: 40px;
  margin: 0 auto 20px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #4285f4;
  border-radius: 50%;
  animation: spin 1s linear infinite;
}

@keyframes spin {
  0% {
    transform: rotate(0deg);
  }

  100% {
    transform: rotate(360deg);
  }
}

.loading-text {
  color: #666;
  font-size: 16px;
}
</style>